<!--注意代码中出现类似 phone 的字样，视为身份证号码-->

<template>
    <!--班级-->
    <div class="class">
        <!--过滤器-->
        <div class="filter-container">
            <div class="filter-item item-input">
                <el-input v-model="classInput" placeholder="请输入班级名称"></el-input>
            </div>
            <div class="filter-item item-button">
                <el-button type="primary" @click="searchClass"><i class="el-icon-search"></i> 搜索</el-button>
            </div>
            <div class="filter-item item-button">
                <el-button type="primary" @click="freshClass"><i class="el-icon-refresh"></i> 刷新</el-button>
            </div>
            <div class="filter-item item-button">
                <el-tooltip content="上传学生名单以创建班级" placement="top">
                    <el-button type="primary" @click="toCreateClass = true"><i class="el-icon-s-flag"></i> 创建班级</el-button>
                </el-tooltip>

            </div>
        </div>

        <!--班级列表，分页处理-->
        <div class="class-list">
            <el-table
                    :data="classDetail.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                    border
                    style="width: 100%">
                <el-table-column
                        label="序号"
                        width="80"
                        align="center">
                    <template slot-scope="scope">
                        {{scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="班级名称"
                        width="280"
                        align="center">
                    <template slot-scope="scope">
                        <el-tooltip content="查看该考试班的学生" placement="top">
                            <span class="col2-cell-style" @click="viewClass((currentPage - 1) * pageSize + scope.$index)">{{scope.row.name}}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="createdTime"
                        label="创建时间"
                        width="280"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="size"
                        label="班级人数"
                        width="240"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="state"
                        label="状态"
                        align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.state === 0" type="success" disable-transitions>正常</el-tag>
                        <el-tag v-if="scope.row.state === 1" type="danger" disable-transitions>禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="320">
                    <template slot-scope="scope">
                        <el-tooltip content="只能添加学生到该考试班，若要添加考生到考试，请到考试管理添加考生" placement="top">
                            <el-button
                                    size="mini"
                                    type="primary"
                                    @click="locateCurClass((currentPage - 1) * pageSize + scope.$index)">添加
                            </el-button>
                        </el-tooltip>
                        <el-button
                                v-if="scope.row.state === 1"
                                size="mini"
                                @click="preEnableClass((currentPage - 1) * pageSize + scope.$index)">启用
                        </el-button>
                        <el-button
                                v-if="scope.row.state === 0"
                                size="mini"
                                type="info"
                                @click="preDisableClass((currentPage - 1) * pageSize + scope.$index)">禁用
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="preDelClass((currentPage - 1) * pageSize + scope.$index)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!--分页-->
        <Pagination :currentPage="currentPage" :pageSize="pageSize" :total="classDetail.length"
                    :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></Pagination>


        <!--创建班级 对话框-->
        <el-dialog title="创建班级" :visible.sync="toCreateClass" top="1vh" width="60%">

            <!--步骤条-->
            <el-steps :active="active" finish-status="success" simple style="margin-bottom: 20px">
                <el-step title="上传学生名单" icon="el-icon-edit"></el-step>
                <el-step title="校验学生名单" icon="el-icon-document"></el-step>
                <el-step title="保存考试班级" icon="el-icon-upload"></el-step>
            </el-steps>

            <!--信息，班级名称，上传班级Excel-->
            <div class="dialog-body-info" v-if="active === 0">
                <el-form ref="classForm" :model="classForm" :rules="classRules" status-icon>
                    <el-form-item label="班级名称" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="classForm.name" autocomplete="off" clearable
                                  placeholder="请输入班级名称"></el-input>
                    </el-form-item>
                </el-form>

                <div class="upload-box" v-if="!fileExsist">
                    <div class="upload-content">
                        <span>请上传学生名单</span>
                        <!--上传-->
                        <el-upload
                                class="file-upload"
                                action=""
                                :multiple="false"
                                :show-file-list="false"
                                accept=".csv"
                                :http-request="httpRequest"
                                :file-list="fileList">
                            <el-button size="small" type="primary">浏览</el-button>
                        </el-upload>
                    </div>
                </div>
            </div>

            <!--上传提示-->
            <div class="upload-tip" v-if="active === 0 || active === 1" :style="active === 0 ? 'margin-left: 5%' : ''">
                不知道怎么填写 CSV 文件？ 请点我
                <a href="../assets/student.csv" download="student.csv">下载模板</a> 上传错误文件？
                <span @click="excelData = [], errExcelData = [], active = 0, fileList = [], fileExsist = false">重新上传CSV文件</span>
            </div>

            <!--校验班级花名册-->
            <div class="dialog-body-table" v-if="active === 1">
                <h3>
                    <i class="el-icon-upload"></i> CSV 文件总共导入 {{excelData.length + errExcelData.length}} 条，成功解析
                    {{excelData.length}} 条
                </h3>
                <!--显示 Excel 中解析成功的学生信息-->
                <el-table
                        :data="excelData"
                        style="width: 100%"
                        max-height="400">
                    <el-table-column
                            prop="考生号"
                            label="考生号"
                            width="180"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="姓名"
                            label="姓名"
                            width="180"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="身份证号码"
                            label="身份证号码"
                            width="200"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="自然班级名称"
                            label="自然班级名称"
                            width="200"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="入学年份"
                            label="入学年份"
                            align="center">
                    </el-table-column>
                </el-table>
                <h3>
                    <i class="el-icon-warning"></i> 共计 {{errExcelData.length}} 条解析失败，橙色为解析出错的地方
                </h3>
                <!--显示 Excel 中解析失败的学生信息-->
                <el-table
                        :data="errExcelData"
                        style="width: 100%"
                        max-height="400"
                        :cell-class-name="tableCellClassName">
                    <el-table-column
                            prop="考生号"
                            label="考生号"
                            width="180"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="姓名"
                            label="姓名"
                            width="180"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="身份证号码"
                            label="身份证号码"
                            width="200"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="自然班级名称"
                            label="自然班级名称"
                            width="200"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="入学年份"
                            label="入学年份"
                            align="center">
                    </el-table-column>
                </el-table>
            </div>

            <!--保存班级-->
            <div class="dialog-body-save" v-if="active === 2">
                <h3>
                    <i class="el-icon-warning"></i>
                    CSV 文件解析完后，解析成功的 {{excelData.length}} 条数据与服务器数据进行对比
                </h3>
                <h3>
                    <i class="el-icon-star-on"></i> 当前状态：<span>对比完成（橙色：考生号重复或已存在，将为学生更新信息，请先仔细核对信息）</span>
                </h3>
                <!--显示与服务器对比后的结果-->
                <el-table
                        :data="parsedExcelData"
                        style="width: 100%"
                        max-height="400"
                        :row-class-name="tableRowClassName">
                    <el-table-column
                            prop="考生号"
                            label="考生号"
                            width="180"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="姓名"
                            label="姓名"
                            width="180"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="身份证号码"
                            label="身份证号码"
                            width="200"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="自然班级名称"
                            label="自然班级名称"
                            width="200"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="入学年份"
                            label="入学年份"
                            align="center">
                    </el-table-column>
                </el-table>
            </div>

            <!--footer 中出现的按钮-->
            <div slot="footer" class="dialog-info-footer" ref="dlgInfoFooter">
                <el-button @click="toCreateClass = false">取 消</el-button>
                <el-button type="primary" @click="prev" v-if="active === 1 || active === 2">上一步</el-button>
                <el-button type="primary" @click="next" v-if="active === 0 || active === 1">下一步</el-button>
                <el-button type="primary" @click="saveClass" v-if="active == 2">保存</el-button>
            </div>

        </el-dialog>

        <!--添加学生 对话框-->
        <el-dialog title="添加学生" :visible.sync="toAddStudent" top="1vh" width="38%" v-if="classDetail.length !== 0">
            <div slot="title" class="header-title">
                <span>添加学生：{{ classTitle }}</span>
            </div>
            <el-form ref="studentForm" :model="studentForm" status-icon :rules="studentRules">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="studentForm.name" autocomplete="off" clearable disabled></el-input>
                </el-form-item>
                <el-form-item label="身份证号码" prop="phone">
                    <el-input v-model="studentForm.phone" autocomplete="off" clearable disabled></el-input>
                </el-form-item>
                <el-form-item label="自然班级名称" prop="nClass">
                    <el-input v-model="studentForm.nClass" autocomplete="off" clearable disabled></el-input>
                </el-form-item>
                <el-form-item label="入学年份" prop="year">
                    <el-input v-model="studentForm.year" autocomplete="off" clearable disabled></el-input>
                </el-form-item>
                <el-form-item label="学号/考生号" prop="id">
                    <el-col :span="10">
                        <el-input v-model="studentForm.id" autocomplete="off" clearable :disabled="!unAddable"
                                  placeholder="请输入学号/考生号"></el-input>
                    </el-col>
                    <el-col :span="4" style="margin-left: 8px">
                        <el-button type="primary" @click="getStudentById"><i class="el-icon-search"></i> 查询</el-button>
                    </el-col>
                    <el-col :span="4">
                        <el-tooltip content="重置表单内容" placement="top">
                            <el-button type="primary" @click="resetAdd"><i class="el-icon-refresh"></i> 重置</el-button>
                        </el-tooltip>

                    </el-col>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAddStudent">取 消</el-button>
                <el-button type="primary" :disabled="unAddable" @click="addStudent(curClassIndex)">添 加</el-button>
            </div>
        </el-dialog>

        <!--查看班级 对话框-->
        <el-dialog title="查看班级" :visible.sync="toViewClass" top="1vh" width="70%" v-if="classDetail.length != 0">
            <div slot="title" class="header-title">
                <span>{{ classTitle }}</span>
            </div>

            <!--过滤栏-->
            <div class="filter-container">
                <el-tooltip content="只能添加学生到该考试班，若要添加考生到考试，请到考试管理添加考生" placement="top">
                    <el-button type="primary" class="filter-item" @click="toAddStudent = true"><i class="el-icon-plus"></i>
                        添加学生
                    </el-button>
                </el-tooltip>
            </div>

            <!--学生表格-->
            <el-table
                    :data="classDetail[curClassIndex].studentData"
                    style="width: 100%"
                    v-if="classDetail.length !== 0 && classDetail[curClassIndex] != null">
                <el-table-column
                        label="序号"
                        width="70"
                        align="center">
                    <template slot-scope="scope">
                        {{scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column
                        label="学号/考生号"
                        prop="id"
                        width="180"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        prop="name"
                        width="140"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="身份证号码"
                        prop="phone"
                        width="180"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="自然班级名称"
                        prop="nClass"
                        width="200"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="入学年份"
                        prop="year"
                        width="80"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="状态"
                        prop="status"
                        align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 0" type="success" disable-transitions>正常</el-tag>
                        <el-tag v-if="scope.row.status == 1" type="danger" disable-transitions>异常</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="130">
                    <template slot-scope="scope">
                        <!--<el-button size="mini" @click="moveStudent(scope.$index)">移动</el-button>-->
                        <el-button size="mini" @click="curStuIndex = scope.$index, toDelStu = true">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!--删除班级 对话框-->
        <el-dialog title="" :visible.sync="toDeleteClass" top="18vh" width="33%" center :show-close="false">
            <div class="delete-header">
                <div class="header-icon">
                    <span class="icon-text">!</span>
                </div>
            </div>
            <div class="delete-tip">是否删除该班级？确定删除后将删除该班级的所有学生以及相关考试数据</div>
            <div slot="footer">
                <el-button type="primary" @click="deleteClass(curClassIndex)">确定删除</el-button>
                <el-button type="info" @click="toDeleteClass = false">取消</el-button>
            </div>
        </el-dialog>

        <!--启用班级 对话框-->
        <el-dialog title="" :visible.sync="toEnableClass" top="18vh" width="33%" center :show-close="false">
            <div class="delete-header">
                <div class="header-icon">
                    <span class="icon-text">!</span>
                </div>
            </div>
            <div class="delete-tip">是否启用该班级？确定启用后该班级可用于组考</div>
            <div slot="footer">
                <el-button type="primary" @click="enableClass(curClassIndex)">确定启用</el-button>
                <el-button type="info" @click="toEnableClass = false">取消</el-button>
            </div>
        </el-dialog>

        <!--禁用班级 对话框-->
        <el-dialog title="" :visible.sync="toDisableClass" top="18vh" width="33%" center :show-close="false">
            <div class="delete-header">
                <div class="header-icon">
                    <span class="icon-text">!</span>
                </div>
            </div>
            <div class="delete-tip">是否禁用该班级？确定禁用后该班级将无法用于组考</div>
            <div slot="footer">
                <el-button type="primary" @click="disableClass(curClassIndex)">确定禁用</el-button>
                <el-button type="info" @click="toDisableClass = false">取消</el-button>
            </div>
        </el-dialog>

        <!--删除学生 对话框-->
        <el-dialog title="" :visible.sync="toDelStu" top="18vh" width="33%" center :show-close="false">
            <div class="delete-header">
                <div class="header-icon">
                    <span class="icon-text">!</span>
                </div>
            </div>
            <div class="delete-tip">是否删除该学生？确定删除后将同时删除该学生相关考试数据</div>
            <div slot="footer">
                <el-button type="primary" @click="deleteStudent(curStuIndex)">确定删除</el-button>
                <el-button type="info" @click="toDelStu = false">取消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import Pagination from './Pagination';
    import Axios from 'axios';
    import XLSX from 'xlsx';
    import jschardet from 'jschardet';
    import Papa from 'papaparse';

    export default {
        name: "",
        data() {
            var checkSid = (rule, value, callback) => {
                if (value == '') {
                    return callback(new Error('学号/考生号不能为空'));
                } else {
                    if (!this.isNumber(value + '')) {
                        callback(new Error('请输入数字值'));
                    } else {
                        if ((value + '').trim().length > 20) {
                            callback(new Error('长度不能超过 20 个字符'));
                        } else {
                            callback();
                        }
                    }
                }
            };
            var checkNClass = (rule, value, callback) => {
                if (value == '') {
                    callback(new Error('班级名称不能为空'));
                } else {
                    if (!this.isEffective(value + '')) {
                        callback(new Error('无效，班级名称不能为null、空字符串或者包含换行符'));
                    } else {
                        if ((value + '').trim().length > 40) {
                            callback(new Error('长度不能超过 40 个字符'));
                        } else {
                            callback();
                        }
                    }
                }
            };
            return {
                fileList: [],
                excelInitLen: '',
                excelParsedLen: '',
                excelData: [],
                errExcelData: [],
                parsedExcelData: [],
                fileExsist: false,
                classInput: '', // 班级搜索框的值
                toCreateClass: false, // 是否创建班级
                toDeleteClass: false, // 是否删除班级
                toEnableClass: false, // 是否启用班级
                toDisableClass: false, // 是否禁用班级
                toDelStu: false, // 是否删除学生
                formLabelWidth: '120px',
                stuOptions: [],
                active: 0,
                classDetail: [],
                currentPage: 1, // 当前页码
                pageSize: 20, // 每页显示条目个数
                classForm: { // 班级表单
                    name: ''
                },
                classRules: { // 班级规则
                    name: [
                        {validator: checkNClass, trigger: 'blur'}
                    ]
                },
                toAddStudent: false, // 是否添加学生
                studentForm: { // 学生表单
                    id: '',
                    name: '',
                    phone: '',
                    nClass: '',
                    year: ''
                },
                studentRules: {
                    id: [
                        {validator: checkSid, trigger: 'blur'}
                    ]
                },
                unAddable: true, // 学生是否可添加
                toViewClass: false, // 是否查看班级
                curClassIndex: 0, // 当前班级索引
                curStuIndex: 0, // 当前学生索引
                classTitle: '' // 班级标题
            }
        },
        components: {
            Pagination
        },
        mounted() {
            if (localStorage.getItem("adminToken") != null) {
                this.requestClassDetail();
            } else {
                this.$router.push({path: "/login"});
            }
        },
        methods: {
            tableRowClassName({row, rowIndex}) {
                if (row.status === 1) {
                    return 'warning-row';
                }
                return '';
            },
            tableCellClassName({row, column, rowIndex, columnIndex}) {
                if (columnIndex === 0 && !this.isNumber(row.考生号 + ''))
                    return 'warning-row';
                else if (columnIndex === 1 && !this.isEffective(row.姓名 + ''))
                    return 'warning-row';
                else if (columnIndex === 2 && !this.isIdNo(row.身份证号码 + ''))
                    return 'warning-row';
                return '';
            },
            //获取班级信息
            requestClassDetail() {
                let api = '/admin/getAllClass';
                Axios({
                    method: 'post',
                    url: api,
                    data: {
                        adminToken: localStorage.getItem("adminToken")
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data === 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    // console.log(res.data);
                    this.classDetail = [];
                    for (let i = res.data.length - 1; i >= 0; i--) {
                        let classes = {};
                        classes.id = res.data[i].class_id;
                        classes.name = res.data[i].class_name;
                        classes.state = res.data[i].class_status;
                        classes.createdTime = this.getTime(res.data[i].class_create_time);
                        classes.size = 0;
                        classes.studentData = [];
                        Axios({
                            method: 'post',
                            url: '/admin/getClassStudent',
                            data: {
                                class_id: classes.id,
                                adminToken: localStorage.getItem("adminToken"),
                            },
                            transformRequest: [
                                function (data) {
                                    let ret = '';
                                    for (let it in data) {
                                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                                    }
                                    ret = ret.substring(0, ret.lastIndexOf('&'));
                                    return ret;
                                }
                            ],
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                        }).then((response) => {
                            if (response.data === 3) {
                                this.$router.push({path: "/login"})
                                return;
                            }
                            for (let j = 0; j < response.data.length; j++) {
                                let student = {};
                                student.id = response.data[j].user_id;
                                student.name = response.data[j].user_name;
                                student.phone = response.data[j].phone_number;
                                student.nClass = response.data[j].n_class;
                                student.year = response.data[j].year;
                                student.status = response.data[j].user_status;
                                classes.studentData.push(student);
                            }
                            classes.size = classes.studentData.length;
                        });
                        this.classDetail.push(classes);
                    }
                }).catch((err) => {
                    console.log(err);
                })
            },
            // 上一步
            prev() {
                --this.active;
                if (this.active < 0) this.active = 0;
            },
            next() {
                if (this.active === 0) {
                    // 为表单绑定验证功能
                    this.$refs['classForm'].validate((valid) => {
                        if (valid) {
                            if (this.fileExsist) {
                                if (this.active++ > 2) this.active = 0;
                            } else
                                this.$message.error('请先上传班级花名册 Excel 文件！');
                        } else {
                            this.$message.error('请先输入班级名称！');
                            return false;
                        }
                    });
                } else if (this.active === 1) {
                    this.checkClass();
                } else {
                    if (this.active++ > 2) this.active = 0;
                }

            },
            // 处理 每页条目个数 的变化
            handleSizeChange(val) {
                this.pageSize = val;
            },
            // 处理 当前页码 的变化
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            // 删除班级预处理
            preDelClass(index) {
                this.curClassIndex = index;
                this.toDeleteClass = true;
            },
            // 启用班级预处理
            preEnableClass(index) {
                this.curClassIndex = index;
                this.toEnableClass = true;
            },
            // 禁用班级预处理
            preDisableClass(index) {
                this.curClassIndex = index;
                this.toDisableClass = true;
            },
            // 定位当前班级，设置添加学生的班级的当前索引
            locateCurClass(index) {
                this.studentForm.id = '';
                this.studentForm.name = '';
                this.studentForm.phone = '';
                this.studentForm.nClass = '';
                this.studentForm.year = '';
                this.curClassIndex = index;
                this.classTitle = this.classDetail[index].name;
                this.unAddable = true;
                this.toAddStudent = true;
            },
            // 获取学生
            getStudentById() {
                this.$refs['studentForm'].validate((valid) => {
                    if (valid) {
                        Axios({
                            method: 'post',
                            url: '/admin/getStudentById',
                            data: {
                                sid: (this.studentForm.id + '').trim(),
                                adminToken: localStorage.getItem("adminToken"),
                            },
                            transformRequest: [
                                function (data) {
                                    let ret = '';
                                    for (let it in data) {
                                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                                    }
                                    ret = ret.substring(0, ret.lastIndexOf('&'));
                                    return ret;
                                }
                            ],
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                        }).then((res) => {
                            if (res.data == 3) {
                                this.$router.push({path: "/login"})
                                return;
                            }
                            // console.log(res.data);
                            // console.log(res.data.user_id == null);
                            if (res.data.user_id == null) {
                                this.studentForm.id = '';
                                this.studentForm.name = '';
                                this.studentForm.phone = '';
                                this.studentForm.nClass = '';
                                this.studentForm.year = '';
                                this.unAddable = true;
                                this.$message.error('学号/考生号不存在，请先在学生管理添加该学生');
                            } else {
                                this.studentForm.id = res.data.user_id;
                                this.studentForm.name = res.data.user_name;
                                this.studentForm.phone = res.data.phone_number;
                                this.studentForm.nClass = res.data.n_class;
                                this.studentForm.year = res.data.year;
                                this.unAddable = false;
                            }
                        }).catch((err) => {
                            this.$message.error('系统内部出错，请联系管理员');
                            console.log(err);
                        });
                    } else {
                        return false;
                    }
                });
            },
            //取消添加学生
            cancelAddStudent() {
                this.resetAdd();
                this.toAddStudent = false;
            },
            resetAdd() {
                this.$refs["studentForm"].resetFields();
                this.unAddable = true;
            },
            // 添加学生
            addStudent(index) {
                Confirm.show("如果该班已经加入考试班级，请到考试管理中添加学生信息", function () {
                    this.$refs['studentForm'].validate((valid) => {
                        if (valid) {
                            Axios({
                                method: 'post',
                                url: '/admin/addStudent',
                                data: {
                                    cid: this.classDetail[index].id,
                                    sid: (this.studentForm.id + '').trim(),
                                    adminToken: localStorage.getItem("adminToken"),
                                },
                                transformRequest: [
                                    function (data) {
                                        let ret = '';
                                        for (let it in data) {
                                            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                                        }
                                        ret = ret.substring(0, ret.lastIndexOf('&'));
                                        return ret;
                                    }
                                ],
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                            }).then((res) => {
                                if (res.data == 3) {
                                    this.$router.push({path: "/login"})
                                    return;
                                }
                                // console.log(res.data);
                                if (res.data == "success") {
                                    this.cancelAddStudent();
                                    this.$message.success('添加成功');
                                    this.requestClassDetail();
                                } else if (res.data == "existed") {
                                    this.$message.warning('学生已在该考试班中，请勿重复添加');
                                }
                            }).catch((err) => {
                                this.$message.error('系统内部出错，请联系管理员');
                                console.log(err);
                            });
                        } else {
                            return false;
                        }
                    });
                });

            },
            // 查看班级
            viewClass(index) {
                this.curClassIndex = index;
                this.classTitle = this.classDetail[index].name;
                this.toViewClass = true;
            },
            //搜索班级
            searchClass() {
                Axios({
                    method: 'post',
                    url: '/admin/searchClass',
                    data: {
                        class_name: this.classInput,
                        adminToken: localStorage.getItem("adminToken"),
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data == 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    this.currentPage = 1;
                    //console.log(res.data);
                    this.classDetail = [];
                    for (let i = res.data.length - 1; i >= 0; i--) {
                        let classes = {};
                        classes.id = res.data[i].class_id;
                        classes.name = res.data[i].class_name;
                        classes.state = res.data[i].class_status;
                        classes.createdTime = this.getTime(res.data[i].class_create_time);
                        classes.size = 0;
                        classes.studentData = [];
                        Axios({
                            method: 'post',
                            url: '/admin/getClassStudent',
                            data: {
                                class_id: classes.id,
                                adminToken: localStorage.getItem("adminToken"),
                            },
                            transformRequest: [
                                function (data) {
                                    let ret = '';
                                    for (let it in data) {
                                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                                    }
                                    ret = ret.substring(0, ret.lastIndexOf('&'));
                                    return ret;
                                }
                            ],
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                        }).then((response) => {
                            if (response.data == 3) {
                                this.$router.push({path: "/login"})
                                return;
                            }
                            for (let j = 0; j < response.data.length; j++) {
                                let student = {};
                                student.id = response.data[j].user_id;
                                student.name = response.data[j].user_name;
                                student.phone = response.data[j].phone_number;
                                student.nClass = response.data[j].n_class;
                                student.year = response.data[j].year;
                                student.status = response.data[j].user_status;
                                classes.studentData.push(student);
                            }
                            classes.size = classes.studentData.length;
                        });
                        this.classDetail.push(classes);
                    }
                })
            },
            // 删除班级
            deleteClass(index) {
                Axios({
                    method: 'post',
                    url: '/admin/deleteClass',
                    data: {
                        class_id: this.classDetail[index].id,
                        adminToken: localStorage.getItem("adminToken"),
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data == 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    // console.log(res.data);
                    this.toDeleteClass = false;
                    this.$notify({
                        title: this.classDetail[index].name,
                        message: '删除成功',
                        type: 'success',
                        duration: 3000
                    });
                    this.classDetail.splice(index, 1);
                }).catch((err) => {
                    console.log(err);
                });
            },
            // 启用班级
            enableClass(index) {
                Axios({
                    method: 'post',
                    url: '/admin/enableClass',
                    data: {
                        class_id: this.classDetail[index].id,
                        adminToken: localStorage.getItem("adminToken"),
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data == 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    // console.log(res.data);
                    this.toEnableClass = false;
                    this.$notify({
                        title: this.classDetail[index].name,
                        message: '启用成功',
                        type: 'success',
                        duration: 3000
                    });
                    this.classDetail[index].state = 0;
                }).catch((err) => {
                    console.log(err);
                });
            },
            // 禁用班级
            disableClass(index) {
                Axios({
                    method: 'post',
                    url: '/admin/disableClass',
                    data: {
                        class_id: this.classDetail[index].id,
                        adminToken: localStorage.getItem("adminToken"),
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data == 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    // console.log(res.data);
                    this.toDisableClass = false;
                    this.$notify({
                        title: this.classDetail[index].name,
                        message: '禁用成功',
                        type: 'success',
                        duration: 3000
                    });
                    this.classDetail[index].state = 1;
                }).catch((err) => {
                    console.log(err);
                });
            },
            // 删除学生
            deleteStudent(index) {
                Axios({
                    method: 'post',
                    url: '/admin/deleteStudent',
                    data: {
                        class_id: this.classDetail[this.curClassIndex].id,
                        user_id: this.classDetail[this.curClassIndex].studentData[index].id,
                        adminToken: localStorage.getItem("adminToken"),
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data == 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    // console.log(res);
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'warning',
                        duration: 3000
                    });
                    this.toDelStu = false;
                    this.classDetail[this.curClassIndex].studentData.splice(index, 1);
                    this.classDetail[this.curClassIndex].size -= 1;
                }).catch((err) => {
                    console.log(err);
                });
            },
            // 移动学生
            moveStudent(index) {
                this.$notify({
                    title: '暂未实现',
                    message: (index + 1) + ' -- 敬请期待',
                    type: 'warning',
                    duration: 3000
                });
            },
            //读取 csv 文件数据
            httpRequest(param) {
                this.fileExsist = true;
                let fileObj = param.file; // 相当于input里取得的files
                let fReader = new FileReader();
                fReader.readAsDataURL(fileObj);
                fReader.onload = evt => {
                    // 检查编码
                    let encoding = this.checkEncoding(evt.target.result);
                    // 将csv转换成二维数组
                    Papa.parse(fileObj, {
                        encoding,
                        complete: res => {
                            // UTF8 \r\n与\n混用时有可能会出问题
                            let data = res.data;
                            if (data[data.length - 1] == "") {
                                //去除最后的空行
                                data.pop();
                            }
                            // console.log(data);
                            //将二维数组转化为学生对象数组
                            for (let i = 1; i < data.length; i++) {
                                let stu = {};
                                stu.考生号 = (data[i][0] + '').trim();
                                stu.姓名 = (data[i][1] + '').trim();
                                //如果是中文名，包括带·的少数民族姓名，则去除中间的空格
                                if (/^[\u4e00-\u9fa5·\s]{1,100}$/.test(stu.姓名))
                                    stu.姓名 = stu.姓名.replace(/\s/g, '');
                                stu.身份证号码 = (data[i][2] + '').trim().replace(/x/g, 'X');
                                stu.自然班级名称 = (data[i][3] + '').trim();
                                stu.入学年份 = (data[i][4] + '').trim();
                                if (this.isNumber(stu.考生号) && this.isEffective(stu.姓名)
                                    && this.isIdNo(stu.身份证号码) && this.isEffective(stu.自然班级名称)
                                    && this.isNumber(stu.入学年份)) {
                                    this.excelData.push(stu);
                                } else {
                                    this.errExcelData.push(stu);
                                }
                            }
                            // console.log(this.excelData, this.errExcelData);
                        }
                    });
                };
                this.$refs['classForm'].validate((valid) => {
                    if (valid) {
                        this.active++;
                    } else {
                        this.$message.error('请先输入班级名称！');
                        return false;
                    }
                });
            },
            // 检查编码，引用了 jschardet
            checkEncoding(base64Str) {
                // 这种方式得到的是一种二进制串
                let str = atob(base64Str.split(";base64,")[1]);
                // 要用二进制格式
                let encoding = jschardet.detect(str);
                encoding = encoding.encoding;
                if (encoding == "windows-1252") {
                    // 有时会识别错误（如UTF8的中文二字）
                    encoding = "ANSI";
                }
                return encoding;
            },
            //刷新页面
            freshClass() {
                this.requestClassDetail();
                this.classInput = '';
                this.currentPage = 1;
            },
            //校验班级，Excel 表与服务器数据进行对比，返回考生状态列表（是否重复或已经存在）
            checkClass() {
                let ids = [];
                for (let i = 0; i < this.excelData.length; i++) {
                    ids.push(this.excelData[i].考生号.trim());
                }
                // console.log(ids);
                Axios({
                    method: 'post',
                    url: '/admin/checkClass',
                    data: {
                        ids: ids,
                        adminToken: localStorage.getItem("adminToken")
                    },
                    transformRequest: [
                        function (data) {
                            let ret = '';
                            for (let it in data) {
                                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                            }
                            ret = ret.substring(0, ret.lastIndexOf('&'));
                            return ret;
                        }
                    ],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }).then((res) => {
                    if (res.data == 3) {
                        this.$router.push({path: "/login"})
                        return;
                    }
                    this.parsedExcelData = this.excelData;
                    this.excelParsedLen = 0;
                    for (let i = 0; i < this.parsedExcelData.length; i++) {
                        this.parsedExcelData[i].status = res.data[i];
                        if (res.data[i] === 0) this.excelParsedLen++;
                    }
                    // console.log(this.parsedExcelData);
                    this.active++;
                }).catch((err) => {
                    this.$notify({
                        title: '错误',
                        message: '班级花名册校验失败！',
                        type: 'error',
                        duration: 3000
                    });
                    console.log(err);
                });
            },
            //新建班级
            saveClass() {
                let ids = [];
                let names = [];
                let phones = [];
                let nClasses = [];
                let years = [];
                for (let i = 0; i < this.parsedExcelData.length; i++) {
                    ids.push(this.parsedExcelData[i].考生号);
                    names.push(this.parsedExcelData[i].姓名);
                    phones.push(this.parsedExcelData[i].身份证号码);
                    nClasses.push(this.parsedExcelData[i].自然班级名称);
                    years.push(this.parsedExcelData[i].入学年份);
                }
                // console.log(ids, names, phones, nClasses, years);
                if (ids.length > 0) {
                    Axios({
                        method: 'post',
                        url: '/admin/saveClass',
                        data: {
                            adminToken: localStorage.getItem("adminToken"),
                            className: (this.classForm.name + '').trim(),
                            ids: ids,
                            names: names,
                            phones: phones,
                            nClasses: nClasses,
                            years: years
                        },
                        transformRequest: [
                            function (data) {
                                let ret = '';
                                for (let it in data) {
                                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                                }
                                ret = ret.substring(0, ret.lastIndexOf('&'));
                                return ret;
                            }
                        ],
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                    }).then((res) => {
                        if (res.data == 3) {
                            this.$router.push({path: "/login"})
                            return;
                        }
                        if (res.data == "success") {
                            this.excelData = [];
                            this.errExcelData = [];
                            this.active = 0;
                            this.fileList = [];
                            this.fileExsist = false;
                            this.classForm.name = '';
                            this.toCreateClass = false;
                            this.$message.success('班级创建成功');
                            this.freshClass();
                        }
                    }).catch((err) => {
                        this.$message.error('系统内部出错，请联系管理员');
                        console.log(err);
                    });
                } else {
                    this.$notify({
                        title: '错误',
                        message: '没有符合条件的考生，请重新上传花名册！',
                        type: 'error',
                        duration: 3000
                    });
                }
            }
        }
    }
</script>

<style scoped>

    @import "../styles/table-row.css";
    @import "../styles/del-confirm.css";


    input[type=file] {
        display: none !important;
    }

    .class {
        width: 100%;
    }

    .filter-container {
        padding-bottom: 10px;
    }

    .filter-item {
        display: inline-block;
        vertical-align: middle;
        margin-bottom: 10px;
    }

    .item-input {
        width: 200px;
        margin-right: 5px;
    }

    .filter-item:nth-child(3), .filter-item:nth-child(4) {
        margin-left: 16px;
    }

    .class-list {
        width: 100%;
    }

    .el-dialog .el-form-item {
        font-weight: 600;
    }

    .dialog-body-info .upload-box {
        width: 94.5%;
        height: 120px;
        margin-left: 5%;
        margin-bottom: 20px;
        font-weight: 100;
        border: 2px #bbb dashed;
        border-radius: 8px;
        display: flex;
        align-items: center;

    }

    .dialog-body-info .upload-content {
        margin: 0 auto;
    }

    .dialog-body-info .upload-content .file-upload {
        display: inline-block;
        margin-left: 1rem;
    }

    .dialog-body-info .upload-content span {
        font-size: 1.5rem;
        color: darkgrey;
    }

    .upload-tip a {
        text-decoration: none;
        color: #409EFF;
    }

    .upload-tip {
        margin-top: 10px;
    }

    .dialog-body-table .el-table {
        margin-top: 20px;
    }

    .dialog-body-save h3 span {
        color: green;
    }

    .dialog-body-save h3 a {
        text-decoration: none;
        color: inherit;
    }

    .class-list .col2-cell-style, .upload-tip span {
        color: #409EFF;
        cursor: pointer;
    }

</style>